<template>
  <div>
    <!--            任务名称-->
    <div class="todo-task-title">
      <v-btn icon :class="'checkbox-completeTask checkbox-' + task.status" @click="completeTask()">
        <v-icon v-show="!(this.task.status === 'done')">fa-square</v-icon>
        <v-icon v-show="this.task.status === 'done'">fa-check-square</v-icon>
      </v-btn>

      <div class="todo-rest">
        <span v-show="!isEditTaskName" @click="
            () => {
              this.isEditTaskName = true;
            }
          ">{{ taskName }}</span>

        <textarea v-show="isEditTaskName" rows="1" class="title-style" placeholder="输入任务标题" @blur.prevent="taskNameTextLoseFocus" @keydown="(e) => keydownTaskName(e)" @keyup="(e) => keyupTaskName(e)" id="todo_content" v-model="taskName"></textarea>
      </div>
    </div>

    <!--            负责人-->
    <div class="main-todo-additions">
      <div class="additions-assignedto">
        <v-list-item-avatar :color="selectMember == '无负责人' ? '' : '#81D4FA'" size="18" :style="{
            transform: 'translateX(16px)',
            border: selectMember == '无负责人' ? '1px dashed' : '',
          }">
          <v-icon v-if="selectMember == '无负责人'" size="18">
            mdi-account
          </v-icon>

          <span style="color:white;font-size:1px;" v-else>{{
              selectMember.length > 1
                ? selectMember.substring(
                    selectMember.length - 1,
                    selectMember.length
                  )
                : selectMember
            }}</span>
        </v-list-item-avatar>
        <el-select v-model="selectMember" placeholder="无负责人" class="select-person" filterable @change="selectMemberChange">
          <el-option v-for="item in taskTeamMemberMetaShow" :label="item.label" :value="item.value" class="el-option">
            <v-list-item-avatar :color="item.value == 0?'':'#81D4FA'" size="18" :style="{'border':item.value == 0?'1px dashed':'','margin-left':'8px'}">
              <v-icon v-if="item.value == 0" size="18">
                mdi-account
              </v-icon>

              <span style="color:white;font-size:1px;transform:translateX(0.5px)" v-else>
                {{
                item.label.length > 1
                  ? item.label.substring(
                      item.label.length - 1,
                      item.label.length
                    )
                  : item.label
              }}</span>
            </v-list-item-avatar>
            <span style="color: #8492a6; font-size: 13px">{{
              item.label
            }}</span>
          </el-option>
        </el-select>
      </div>

      <!--                截止时间-->
      <div class="additions-endtime">
        <el-date-picker value-format="yyyy-MM-dd" v-model="endtimeVal" type="date" placeholder="选择截止日期" @change="
            (val) => {
              this.updateDeadline({ deadline: val ? val : '' });
            }
          " width="155px" class="pickerOptions" :picker-options="expireTimeOption"></el-date-picker>
      </div>
      <!--优先级-->
      <div class="additions-pri">
        <v-icon color="red darken-2" v-show="priority === 1">mdi-alert-outline</v-icon>
        <v-icon color="orange darken-1" v-show="priority === 2">mdi-alert-outline</v-icon>
        <v-icon color="grey lighten-1" v-show="priority === 3">mdi-alert-outline</v-icon>
        <v-icon color="green darken-1" v-show="priority === 4">mdi-alert-outline</v-icon>
        <el-select v-model="priority" placeholder="优先级" :class="'select-pri select-pri' + priority" filterable clearable @change="
            (val) => {
              this.priorityChange(val);
            }
          ">
          <el-option v-for="item in priMetaShow" :label="item.label" :value="item.value" class="el-option">
            <div class="pri-itemicon" :style="
                'margin-left: 10px;margin: 5px 5px;border-radius: 25%;width: 25px; height: 25px; float: left; background:' +
                  item.color
              "></div>
            <span class="pri-itemtext" style="font-size: 13px;color: #8492a6">{{
              item.label
            }}</span>
          </el-option>
        </el-select>
      </div>
    </div>

      <!-- 标签 -->
      <div class="label-type">
          <v-icon size="18" color="grey darken-1" style="margin-right: 10px">fa fa-tag</v-icon>
          <v-chip v-if="selectedItem.id" small :style="'background:' +selectedItem.color" text-color="white" @click:close="clearType">{{selectedItem.text}}</v-chip>
          <el-popover placement="bottom-start"  width="200" height="60" trigger="click" slot="append">
              <el-row style="margin-left: 0px;">
                  <v-list >
                      <v-list-item-group v-model="selectedItem.value">
                          <v-list-item  v-for="(item, i) in typeItems" :key="i" :value="item.value" @click="changeType(item)">
                              <template v-slot:default="{ active, }">
                                  <v-list-item-action>
                                      <v-checkbox :input-value="active" color="primary"></v-checkbox>
                                  </v-list-item-action>
                                  <v-chip :style="'margin-left: 30px;background:' +item.color" text-color="white" >{{item.text}}</v-chip>
                              </template>
                          </v-list-item>
                      </v-list-item-group>
                  </v-list>
              </el-row>
              <a class="row-click" slot="reference">
                  <span class="mdc-chip__text">修改类型</span>
              </a>
          </el-popover>


      </div>

    <!--            任务描述-->
    <div class="todo-task-detail">
      <div class="row-title" v-show="!isTaskDetailEdit">
        <v-icon size="18" color="grey darken-1">fa fa-file-text-o</v-icon>
        <span>任务描述</span>
        <a class="row-link" @click="taskDetailEditStatus('edit')">编辑</a>
      </div>
      <div class="desc-wrapper" v-show="!isTaskDetailEdit">
        <div class="container editor-style gallery-wrap desc-content" v-html="
            task ? (task.desc ? task.desc : noDescription) : noDescription
          "></div>
      </div>

      <div class="task-detail-richtext" v-show="isTaskDetailEdit">
        <app-richtexteditor-comment :value="task ? task.desc : ''" :data="JSON.stringify({ data: '1' })" @change="
            (val) => {
              taskDetailRichTextChange(val);
            }
          " ref="taskDetailRichtext" :height="266" :placeholder="taskDetailPlaceholder" name="discuss" :uploadparams="{ objecttype: 'task', version: 'editor' }" :exportparams="{ objecttype: 'task', version: 'editor' }" style="">
        </app-richtexteditor-comment>

        <v-btn class="save" color="cyan darken-1 " @click="taskDetailEditStatus('save')">保存</v-btn>
        <v-btn class="cancel" color="grey" @click="taskDetailEditStatus('cancel')">取消</v-btn>
      </div>

      <div class="taskDetail-file">
        <el-upload class="upload-taskDetail-file" :action="uploadUrl" multiple :on-remove="handleRemove" :before-remove="beforeRemove" :on-change="handleChange" :on-preview="handlePreview" :data="{ objecttype: 'task', version: '1', objectid: this.task.id }" :file-list="fileList">
          <i class="el-icon-link"></i><a class="row-link">上传新附件</a>
          <i class="el-icon-link" style="margin-left: 20px;" v-show="showDownloadAllFiles"></i>
          <a class="row-link" @click="downloadAllFiles" v-show="showDownloadAllFiles">下载所有附件</a>
        </el-upload>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Model } from "vue-property-decorator";
import TaskService from "@service/task/task-service";
import { Environment } from "@/environments/environment";
import CodeListService from "@codelist/codelist-service";
import ProjectTeamServiceBase from "@service/project-team/project-team-service-base";

@Component({})
export default class AppTaskdetail extends Vue {

    /**
     * 实体服务对象
     *
     * @type {TaskService}
     * @memberof AppTaskdetail
     */
    public appEntityService: TaskService = new TaskService();

    /**
     * 项目团队对象
     * @type {ProjectTeamServiceBase}
     * @memberof AppTaskdetail
     */
    public projectTeamServiceBase: ProjectTeamServiceBase = new ProjectTeamServiceBase();

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof AppTaskdetail
     */
    @Prop() public viewparams!: any;

    /**
     * 视图上下文
     *
     * @type {*}
     * @memberof AppTaskdetail
     */
    @Prop() public context!: any;

    /**
     * 任务数据
     * @type {*}
     * @memberof AppTaskdetail
     */
    public task: any = {status: ""};

    /**
     * 截止时间
     * @type {*}
     * @memberof AppTaskdetail
     */
    public endtimeVal: string = "";

    /**
     * 是否完成任务，默认为否
     * @type {boolean}
     * @memberof AppTaskdetail
     */
    public isTaskDone: boolean = false;

    /**
     * 是否可以点击任务完成Checkbox
     * @type {boolean}
     * @memberof AppTaskdetail
     */
    public enableTaskStatusCheck: boolean = false;

    /**
     * 任务名称
     * @type {string}
     * @memberof AppTaskdetail
     */
    public taskName: string = "";

    /**
     * 负责人
     *  @type {string}
     * @memberof AppTaskdetail
     */
    public selectMember: string = "";

    /**
     * 下拉列表应该显示的团队成员
     * @type {Array<any>}
     * @memberof AppTaskdetail
     */
    public taskTeamMemberMetaShow: Array<any> = [];

    /**
     * 所有团队成员
     * @type {Array<any>}
     * @memberof AppTaskdetail
     */
    public taskTeamMemberMetaAll: Array<any> = [];

    /**
     * 优先级
     * 当前选中值
     * @type {string}
     * @memberof AppTaskdetail
     */
    priority: string = "";

    /**
     * 是否正在编辑任务名称，默认false
     * @type {boolean}
     * @memberof AppTaskdetail
     */
    public isEditTaskName: boolean = false;

    /**
     * 团队成员相关变量、方法
     * @type {string}
     * @memberof AppTaskdetail
     */
    public searchValue: string = "";

    /**
     * 上传路径
     * @type {string}
     * @memberof AppTaskdetail
     */
    public uploadUrl: string = Environment.BaseUrl + Environment.UploadFile;

    /**
     * 下载路径
     * @type {string}
     * @memberof AppTaskdetail
     */
    public exportFileUrl: string = Environment.BaseUrl + Environment.ExportFile;

    /**
     * 代码表service
     * * @type {CodeListService}
     * @memberof AppTaskdetail
     */
    public codeListService: CodeListService = new CodeListService({
        $store: this.$store,
    });

    /**
     * 文件列表
     * @type {Array<any>}
     * @memberof AppTaskdetail
     */
    public fileList: Array<any> = [];

    /**
     * 显示下载所有附件
     * @type {boolean}
     * @memberof AppTaskdetail
     */
    public showDownloadAllFiles: boolean = false;

    /**
     * 优先级代码项
     * @type {Array<any>}
     * @memberof AppTaskdetail
     */
    public priMetaShow: Array<any> = [];

    /**
     * 类型type代码项
     * @type {Array<any>}
     * @memberof AppTaskdetail
     */
    public selectedItem :any= {};

    /**
     * 类型
     * @type {Array<any>}
     * @memberof AppTaskdetail
     */
    public typeItems: Array<any> = [];

    /**
     * 声明周期
     * @memberof AppTaskdetail
     */
    public created() {
        let taskId = this.context.task;
        if (!taskId) {
            taskId = this.viewparams.taskId;
        }
        if (taskId) {
            // 查询附件信息
            this.searchAnnexFiles(taskId);

            // 查询任务信息
            this.searchTaskByTaskId(taskId);

            // 优先级代码表
            let pritCodelist = this.getpritCodelist();
            this.priMetaShow = pritCodelist;

            this.gettypetCodelist();
        }
    }

    /**
     * 清空类型
     * @memberof AppTaskdetail
     */
    public clearType(){
        this.selectedItem = {};
        this.updateType();
    }

    /**
     * 类型改变
     * @param {string} [item] 所点击项
     * @memberof AppTaskdetail
     */
    public changeType(item:any){
        if(item.id === this.selectedItem.id){
            this.selectedItem = {};
        }else{
            this.selectedItem = item;
        }
        this.updateType();
    }

    /**
     * 更新类型类型
     * @memberof AppTaskdetail
     */
    public updateType(){
        let args = {type: this.selectedItem.value ? this.selectedItem.value : ''};
        let context: any = {task: this.task.id};
        let data = this.task;
        Object.assign(data, args);
        let isloading = true;
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            result = this.appEntityService.UpdateType(context, data, isloading);
            result
                .then((response) => {
                    if (response.status === 200) {
                        // this.$emit("getActionData", this.task.id);
                        this.searchTaskByTaskId(this.task.id);
                        // 清除其他页面缓存
                        this.$store.commit("removeOtherPage");
                    }
                })
                .catch((response) => {
                    if (response && response.status === 500) {
                        const url: any = "/500";
                        this.$router.push({path: url});
                    } else {
                        this.$Notice.error({title: "错误", desc: response.data.message});
                        reject(response);
                    }
                });
        });
    }

    /**
     * 代码表转换
     * @param {string} [value] 代码项
     * @memberof AppTaskdetail
     * @return 代码项text值
     */
    public getTypeItem(value: string) {
        let item = {};
        for (let i = 0; i < this.typeItems.length; i++) {
            if (this.typeItems[i].id == value) {
                item = this.typeItems[i];
            }
        }
        this.selectedItem = item;
    }

    /**
     * 代码表转换
     * @param {string} [item] 代码项
     * @memberof AppTaskdetail
     * @return 代码项text值
     */
    public getPriText(item: any) {
        let actionTypeCodelist: any = this.getpritCodelist();
        let text = "";
        for (let i = 0; i < actionTypeCodelist.length; i++) {
            if (actionTypeCodelist[i].id == item.action) {
                text = actionTypeCodelist[i].label;
            }
        }
        return text;
    }

    /**
     * 获取type代码表
     *
     * @memberof AppTaskdetail
     * @return 代码表数组
     */
    public gettypetCodelist() {
        const codelist = this.$store.getters.getCodeList("Task__type");
        if (codelist) {
            let items: Array<any> = [...JSON.parse(JSON.stringify(codelist.items))];
            this.typeItems = items;
        } else {
            console.log(`----task__type----代码表不存在`);
            return [];
        }
    }

    /**
     * 获取优先级代码表
     *
     * @memberof AppTaskdetail
     * @return 代码表数组
     */
    public getpritCodelist() {
        const codelist = this.$store.getters.getCodeList("Task__pri");
        if (codelist) {
            let items: Array<any> = [...JSON.parse(JSON.stringify(codelist.items))];
            return items;
        } else {
            console.log(`----Task__pri----代码表不存在`);
            return [];
        }
    }

    /**
     * 优先级修改，更新任务
     * @param {string} [val] 优先级
     * @memberof AppTaskdetail
     */
    public priorityChange(val: string) {
        let args = {pri: val};
        let context: any = {task: this.task.id};
        let data = this.task;
        Object.assign(data, args);
        let isloading = true;
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            result = this.appEntityService.UpdatePri(context, data, isloading);
            result
                .then((response) => {
                    if (response.status === 200) {
                        // this.$emit("getActionData", this.task.id);
                        this.searchTaskByTaskId(this.task.id);
                    }
                })
                .catch((response) => {
                    if (response && response.status === 500) {
                        const url: any = "/500";
                        this.$router.push({path: url});
                    } else {
                        this.$Notice.error({title: "错误", desc: response.data.message});
                        reject(response);
                    }
                });
        });
    }

    /**
     * el-file 文件状态改变时
     * @param file    当前文件对象
     * @param fileList    文件对象列表
     */
    public handleChange(file: any, fileList: any) {
        this.fileList = fileList;
        this.showDownloadAllFiles = this.fileList.length > 1;
        this.$forceUpdate();
    }

    /**
     * 点击文件（下载）
     * @param {any} [file] 当前文件对象
     * @memberof AppTaskdetail
     */
    public handlePreview(file: any) {
        let fileid = file.fileid;
        if (fileid) {
            window.open(`${this.exportFileUrl}/${fileid}`);
        } else {
            fileid = file.response.id;
            if (fileid) {
                window.open(`${this.exportFileUrl}/${fileid}`);
            }
        }
    }

    /**
     * 下载所有附件
     * @memberof AppTaskdetail
     */
    public downloadAllFiles() {
        for (let i = 0; i < this.fileList.length; i++) {
            let file: any = this.fileList[i];
            let fileid = file.fileid;
            if (fileid) {
                window.open(`${this.exportFileUrl}/${fileid}`);
            } else {
                fileid = file.response.id;
                if (fileid) {
                    window.open(`${this.exportFileUrl}/${fileid}`);
                }
            }
        }
    }

    /**
     * 文件移除 钩子函数
     * @param {any} [file] 当前文件对象
     * @param fileList    文件对象列表
     * @memberof AppTaskdetail
     */
    public handleRemove(file: any, fileList: any) {
    }

    /**
     * 移除之前
     * @param {any} [file] 当前文件对象
     * @param {any} fileList    文件对象列表
     * @memberof AppTaskdetail
     */
    public beforeRemove(file: any, fileList: any) {
        return this.$confirm(`确定移除 ${file.name}？`, "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            let fileid = file.fileid;
            if (!fileid) {
                fileid = file.response.id;
            }
            if (!fileid) {
                return false;
            }
            return new Promise((resolve: any, reject: any) => {
                let context = {fileid: fileid};
                let result: Promise<any> = this.appEntityService.deleteFileList(
                    context,
                    {},
                    true
                );
                result
                    .then((response) => {
                        if (response && response.status === 200) {
                            console.log("删除成功");
                            resolve(true);
                        }
                    })
                    .catch((response) => {
                        if (response && response.status === 500) {
                            const url: any = "/500";
                            this.$router.push({path: url});
                        } else {
                            this.$Notice.error({
                                title: "错误",
                                desc: response.data.message,
                            });
                            reject(response);
                        }
                    });
            });
        });
    }

    /**
     * 失去焦点之后,更新任务名称
     * @memberof AppTaskdetail
     */
    public taskNameTextLoseFocus() {
        this.isEditTaskName = false;
        // console.log('更新任务名称');
        if (this.taskName && this.taskName != this.task.name) {
            this.updateTaskName({name: this.taskName});
        }
        this.$forceUpdate();
    }

    /**
     * 避免回车键换行
     * @param {any} e  按下的键
     * @memberof AppTaskdetail
     */
    public keydownTaskName(e: any) {
        if (e.keyCode === 13) {
            // 避免回车键换行
            e.preventDefault();
        }
    }

    /**
     * 更新任务名称
     * @param {any} e  按下的键
     * @memberof AppTaskdetail
     */
    public keyupTaskName(e: any) {
        if (e.keyCode === 13) {
            this.isEditTaskName = false;
            // console.log('更新任务名称');
            if (this.taskName && this.taskName != this.task.name) {
                this.updateTaskName({name: this.taskName});
            }
        }
    }

    /**
     * 点击编辑任务 提示语
     * @type {string}
     * @memberof AppTaskActiondata
     */
    public taskDetailPlaceholder: string = "点击编辑任务";
    /**
     * 任务描述(task.desc)，临时存储变量
     * @type {string}
     * @memberof AppTaskActiondata
     */
    public temptaskDetailRichtextContent: string = "";

    /**
     * 任务区域 是否正在编辑
     * @type {boolean}
     * @memberof AppTaskActiondata
     */
    public isTaskDetailEdit: boolean = false;

    /**
     * 暂无描述
     * @type {string}
     * @memberof AppTaskActiondata
     */
    public noDescription: string =
        "<p style='margin-left: 25px;color: #777'>暂无描述</p>";

    /**
     * 任务区域 编辑、保存、取消 点击事件
     * @param {string} tag  要进行的操作标记
     * @memberof AppTaskdetail
     */
    public taskDetailEditStatus(tag: string) {
        if (tag == "save") {
            if (this.temptaskDetailRichtextContent != this.task.desc) {
                let args = {desc: this.temptaskDetailRichtextContent, notToLoginPage:true};
                let context: any = {task: this.task.id};
                let data = {};
                Object.assign(data, args);
                let isloading = true;
                return new Promise((resolve: any, reject: any) => {
                    let result: Promise<any>;
                    result = this.appEntityService.UpdateDesc(context, data, isloading);
                    result.then((response) => {
                        if (response.status === 200) {
                            // this.$emit("getActionData", this.task.id);
                            this.searchTaskByTaskId(this.task.id);
                            // 编辑状态改变
                            this.isTaskDetailEdit = !this.isTaskDetailEdit;
                        }
                    }).catch((response) => {
                        if(response.status === 401){
                            this.$Notice.error({title: "未登录", desc: '编辑区域内容请先复制另存！请手动退出并重新登录。'});
                        }else{
                            this.$Notice.error({title: "错误", desc: '编辑区域内容请先复制另存！' + response.data.message});
                        }
                        reject(response);
                    });
                });
            }else{
                // 编辑状态改变
                this.isTaskDetailEdit = !this.isTaskDetailEdit;
            }
        } else if (tag == "cancel") {
            // 编辑状态改变
            this.isTaskDetailEdit = !this.isTaskDetailEdit;
        } else if (tag == "edit") {
            // 编辑状态改变
            this.isTaskDetailEdit = !this.isTaskDetailEdit;
        }
    }

    /**
     * 任务描述值变化
     * @param {string} val  任务描述
     * @memberof AppTaskdetail
     */
    public taskDetailRichTextChange(val: string) {
        this.temptaskDetailRichtextContent = val;
    }

    /**
     * 点击完成任务（当任务未完成时）,点击激活任务（当任务已完成时）
     * @memberof AppTaskdetail
     */
    public completeTask() {
        if (this.task.status === "cancel" || this.task.status === "closed") {
            return;
        }
        // 重新开始,激活任务
        if (this.isTaskDone) {
            let context: any = {task: this.task.id};
            // ACTION_PARAMS_ACTIVATE.put("assignedTo", null);
            // ACTION_PARAMS_ACTIVATE.put("left", null);
            // ACTION_PARAMS_ACTIVATE.put("comment", "");
            let params: any = {
                id: this.task.id,
                left: 5,
                assignedto: this.task.assignedto,
                comment: "",
            };
            let data = {};
            Object.assign(data, params);
            let isloading = true;
            return new Promise((resolve: any, reject: any) => {
                let result: Promise<any>;
                result = this.appEntityService.Activate(context, data, isloading);
                result
                    .then((response) => {
                        // console.log(response);
                        if (response.data) {
                            // this.task.status = 'doing';
                            // this.$emit("getActionData", this.task.id);
                            this.searchTaskByTaskId(this.task.id);
                            this.$emit("refreshTaskHeadData", this.task.id);
                            // 清除其他页面缓存
                            this.$store.commit("removeOtherPage");
                        } else {
                        }
                    })
                    .catch((response) => {
                        if (response && response.status === 500) {
                            const url: any = "/500";
                            this.$router.push({path: url});
                        } else {
                            this.$Notice.error({
                                title: "错误",
                                desc: response.data.message,
                            });
                            reject(response);
                        }
                    });
            });
        }
        // 完成任务
        else {
            let context: any = {task: this.task.id};
            /*ACTION_PARAMS_FINISH.put("currentConsumed", null) ;本次消耗 Double
                      ACTION_PARAMS_FINISH.put("consumed", null); 总计消耗    Double
                      ACTION_PARAMS_FINISH.put("assignedTo", null);   指派给 string
                      ACTION_PARAMS_FINISH.put("finishedDate", null);   实际完成 yyyy-MM-dd
                      ACTION_PARAMS_FINISH.put("comment", ""); 备注 string*/
            let currentconsumed = 2;
            let consumed = this.task.consumed ? this.task.consumed : 2;
            let totaltime = currentconsumed + consumed;
            let params: any = {
                currentconsumed: currentconsumed,
                consumed: consumed,
                assignedto: this.task.assignedto,
                finisheddate: this.getNowFormatDate2(),
                comment: "",
                id: this.task.id,
                totaltime: totaltime,
                multiple: "0",
            };
            let data = {};
            Object.assign(data, params);
            let isloading = true;
            return new Promise((resolve: any, reject: any) => {
                let result: Promise<any>;
                result = this.appEntityService.Finish(context, data, isloading);
                result
                    .then((response) => {
                        // console.log(response);
                        if (response.data) {
                            // this.task.status = 'done';
                            // this.$emit("getActionData", this.task.id);
                            this.searchTaskByTaskId(this.task.id);
                            this.$emit("refreshTaskHeadData", this.task.id);
                            // 清除其他页面缓存
                            this.$store.commit("removeOtherPage");
                        } else {
                        }
                    })
                    .catch((response) => {
                        if (response && response.status === 500) {
                            const url: any = "/500";
                            this.$router.push({path: url});
                        } else {
                            this.$Notice.error({
                                title: "错误",
                                desc: response.data.message,
                            });
                            reject(response);
                        }
                    });
            });
        }
    }

    /**
     * 截止时间修改
     * @param {string} newval  时间值
     * @memberof AppTaskdetail
     */
    public endtimeChange(newval: string) {
        console.log(newval);
    }

    /**
     * 更新截止时间
     * @param {any} args  截止日期对象
     * @memberof AppTaskdetail
     */
    public updateDeadline(args: any) {
        let context: any = {task: this.task.id};
        let data = this.task;
        Object.assign(data, args);
        let isloading = true;
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            result = this.appEntityService.UpdateDeadline(context, data, isloading);
            result
                .then((response) => {
                    if (response.status === 200) {
                        // this.$emit("getActionData", this.task.id);
                        this.searchTaskByTaskId(this.task.id);
                        // 清除其他页面缓存
                        this.$store.commit("removeOtherPage");
                    }
                })
                .catch((response) => {
                    if (response && response.status === 500) {
                        const url: any = "/500";
                        this.$router.push({path: url});
                    } else {
                        this.$Notice.error({title: "错误", desc: response.data.message});
                        reject(response);
                    }
                });
        });
    }

    /**
     * 更新任务名称
     * @param {any} args  任务名称对象
     * @memberof AppTaskdetail
     */
    public async updateTaskName(args: any) {
        let context: any = {task: this.task.id};
        let data = this.task;
        Object.assign(data, args);
        let isloading = true;
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            result = this.appEntityService.UpdateName(context, data, isloading);
            result
                .then((response) => {
                    if (response.status === 200) {
                        // this.$emit("getActionData", this.task.id);
                        this.searchTaskByTaskId(this.task.id);
                        // 清除其他页面缓存
                        this.$store.commit("removeOtherPage");
                    }
                })
                .catch((response) => {
                    if (response && response.status === 500) {
                        const url: any = "/500";
                        this.$router.push({path: url});
                    } else {
                        this.$Notice.error({title: "错误", desc: response.data.message});
                        reject(response);
                    }
                });
        });
    }

    /**
     * 设置日期选择器不能选择以往的日期
     *
     * @type {any}
     * @memberof AppTaskdetail
     */
    public expireTimeOption: any = {
        disabledDate(date: any) {
            //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
            return date.getTime() < Date.now() - 8.64e7;
        },
    };

    /**
     * 重新指派人员
     * @param {any} item  所选择的项
     * @memberof AppTaskdetail
     */
    public async selectMemberChange(item: any) {
        let context: any = {task: this.task.id};
        /*ACTION_PARAMS_ASSIGNTO.put("assignedTo", null); 指派给 string
                ACTION_PARAMS_ASSIGNTO.put("left", null);   预计剩余  Double
                ACTION_PARAMS_ASSIGNTO.put("comment", ""); 备注 string

                ACTION_URL_PARAMS_ASSIGNTO.add("project");  所属项目
                ACTION_URL_PARAMS_ASSIGNTO.add("id");
                */
        let params: any = {assignedTo: item, left: "8", comment: ""};
        let data = {};
        Object.assign(data, params);
        let isloading = true;
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            result = this.appEntityService.AssignTo(context, data, isloading);
            result
                .then((response) => {
                    if (response.data) {
                        // 调用 重新获取task数据和action记录
                        // this.$emit("getActionData", this.task.id);
                        this.searchTaskByTaskId(this.task.id);
                        // 清除其他页面缓存
                        this.$store.commit("removeOtherPage");
                    }
                })
                .catch((response) => {
                    if (response && response.status === 500) {
                        const url: any = "/500";
                        this.$router.push({path: url});
                    } else {
                        this.$Notice.error({title: "错误", desc: response.data.message});
                        reject(response);
                    }
                });
        });
    }

    /**
     *分页对象
     *@memberof AppTaskdetail
     */
    private page: any = {
        size: 1000,
        page: 0,
    };

    /**
     * 查询附件信息
     * @param {string} taskId  任务id、
     * @memberof AppTaskdetail
     */
    public searchAnnexFiles(taskId: string) {
        return new Promise((resolve: any, reject: any) => {
            let data = {
                srfparentdename: "Task",
                srfparentkey: taskId,
                objecttype: "task",
            };
            Object.assign(data, this.page);
            let result: Promise<any> = this.appEntityService.getFileList(
                {},
                data,
                true
            );
            result
                .then((response) => {
                    if (response && response.status === 200) {
                        let ret: any = response.data;
                        for (let i = 0; i < ret.length; i++) {
                            let fileparam: any = {
                                name: ret[i].title,
                                fileid: ret[i].id,
                                size: ret[i].id.size,
                                extension: ret[i].extension,
                            };
                            this.fileList.push(fileparam);
                        }
                        this.showDownloadAllFiles = this.fileList.length > 1;
                    }
                })
                .catch((response) => {
                    if (response && response.status === 500) {
                        const url: any = "/500";
                        this.$router.push({path: url});
                    } else {
                        this.$Notice.error({title: "错误", desc: response.data.message});
                        reject(response);
                    }
                });
        });
    }

    /**
     * 获取动态代码表UserRealName
     *
     * @memberof AppTaskdetail
     */
    public async getCodeList() {
        this.taskTeamMemberMetaAll = [];
        let codeList: any = this.codeListService.getItems("UserRealName");
        await codeList
            .then((items: any) => {
                if (items && items.length > 0) {
                    //this.userslist.push(...items);
                    this.taskTeamMemberMetaAll = items;
                }
            })
            .catch((error: any) => {
                console.log(error);
            });
        await this.getTaskTeam();
    }

    /**
     * 获取任务团队成员
     *
     * @param {string} [taskId] 任务id
     * @memberof AppTaskdetail
     */
    public async getTaskTeam(taskId?: string): Promise<any> {
        let context: any = {};
        let params: any = {
            srfparentdename: "Project",
            srfparentkey: this.task.project,
            project: this.task.project,
            multiple: 0,
            n_root_eq: this.task.project,
        };
        Object.assign(params, this.page);
        let isloading: any = true;

        await this.projectTeamServiceBase
            .FetchDefault(context, params, isloading)
            .then((response) => {
                if (response && response.status === 200) {
                    if (response.data) {
                        this.taskTeamMemberMetaShow = [];
                        let no_member = {icon: "", value: 0, label: "无负责人"};
                        this.taskTeamMemberMetaShow.push(no_member);
                        let assignedto = no_member.label;
                        for (let i = 0; i < response.data.length; i++) {
                            let account = response.data[i].account;
                            // let avatar = response.data[i].avatar;
                            let avatar = response.data[i].account;
                            // let realname = response.data[i].realname;
                            let realname = response.data[i].account;
                            let commiter = response.data[i].commiter;
                            this.taskTeamMemberMetaAll.forEach((useritme: any) => {
                                if (Object.is(useritme.value, account)) {
                                    realname = useritme.label;
                                }
                                if (useritme.value == this.task.assignedto) {
                                    assignedto = useritme.label;
                                }
                            });
                            let member: any = {
                                icon: avatar,
                                value: account,
                                label: realname,
                                commiter: commiter,
                            };
                            if (account == this.task.assignedto) {
                                assignedto = realname;
                            }
                            this.taskTeamMemberMetaShow.push(member);
                        }
                        // console.log("taskTeamMemberMetaShow:" + JSON.stringify(this.taskTeamMemberMetaShow));
                        this.selectMember = assignedto;
                    }
                }
            })
            .catch((response) => {
                if (response && response.status === 500) {
                    const url: any = "/500";
                    this.$router.push({path: url});
                } else {
                    this.$Notice.error({title: "错误", desc: response.data.message});
                }
            });
    }

    /**
     * 查找任务
     * @param taskId 任务id
     * @memberof AppTaskdetail
     */
    public searchTaskByTaskId(taskId: string) {
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            result = this.appEntityService.searchTaskByTaskId(
                "tasks/" + taskId,
                {},
                true
            );
            result
                .then((response) => {
                    if (response && response.status === 200) {
                        if (response.data && response.data.id) {
                            if (
                                JSON.stringify(response.data) &&
                                JSON.stringify(response.data).length > 0
                            ) {
                                this.task = response.data;
                                this.taskName = response.data.name;
                                this.endtimeVal = response.data.deadline;
                                this.priority = response.data.pri;
                                this.getTypeItem(response.data.type);

                                this.isTaskDone =
                                    this.task.status === "done" ||
                                    this.task.status === "cancel" ||
                                    this.task.status === "closed";
                                if (
                                    this.task.status === "cancel" ||
                                    this.task.status === "closed"
                                ) {
                                    this.enableTaskStatusCheck = true;
                                } else {
                                    this.enableTaskStatusCheck = false;
                                }

                                // 任务描述中的desc格式改变
                                const url =
                                    this.exportFileUrl.indexOf("../") === 0
                                        ? this.exportFileUrl.substring(3)
                                        : this.exportFileUrl;
                                let desc = this.task.desc.replace(
                                    /\{(\d+)\.(bmp|jpg|jpeg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp)\}/g,
                                    `${url}/$1`
                                );
                                this.task.desc = desc;

                                this.getCodeList();
                            }
                        } else {
                            // const url: any = '/404';
                            // this.$router.push({path: url});
                            this.$Notice.error({
                                title: "提示",
                                desc: "该任务不存在，没有这个任务！",
                            });
                        }
                    }
                })
                .catch((response) => {
                    if (response && response.status === 500) {
                        const url: any = "/500";
                        this.$router.push({path: url});
                    } else {
                        this.$Notice.error({title: "错误", desc: response.data.message});
                        reject(response);
                    }
                });
        });
    }

    /**
     * 获取指定时间格式 yyyy-mm-dd
     */
    public getNowFormatDate2() {
        let date = new Date();
        let seperator1 = "-";
        let seperator2 = ":";
        let month: any = date.getMonth() + 1;
        let strDate: any = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        return date.getFullYear() + seperator1 + month + seperator1 + strDate;
    }
}
</script>

<style lang="less">
@import "./app-taskdetail.less";
</style>
